﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Net;
using System.Windows;
using System.Windows.Controls;
using System.Windows.Documents;
using System.Windows.Input;
using System.Windows.Media;
using System.Windows.Media.Animation;
using System.Windows.Shapes;
using Microsoft.Phone.Controls;
using OpenXLive.Silverlight;
using OpenXLive;

namespace MushroomPicker
{
    public enum GameState
    {
        Ready, Showing, Ending, Lose
    }
    public partial class Game : PhoneApplicationPage
    {
        public static Random Random = new Random((int)DateTime.Now.Ticks);
        public Game()
        {
            InitializeComponent();
            this.Loaded += new RoutedEventHandler(Game_Loaded);

            GameState = MushroomPicker.GameState.Ending;
            foreach (var item in gamecanves.Children)
            {
                //item.MouseLeftButtonDown += new MouseButtonEventHandler(item_MouseLeftButtonDown);
            }
        }
        protected override void OnNavigatedTo(System.Windows.Navigation.NavigationEventArgs e)
        {
            Touch.FrameReported += new TouchFrameEventHandler(Touch_FrameReported);
            base.OnNavigatedTo(e);
        }
        protected override void OnNavigatedFrom(System.Windows.Navigation.NavigationEventArgs e)
        {
            Sound.PlayExit();
            Touch.FrameReported -= (Touch_FrameReported);
            base.OnNavigatedFrom(e);
        }
        private void ShowAll()
        {
            foreach (var item in gamecanves.Children)
            {
                item.Visibility = System.Windows.Visibility.Visible;
            }
        }
        //void item_MouseLeftButtonDown(object sender, MouseButtonEventArgs e)
        //{
        //    if (GameState != MushroomPicker.GameState.Ready)
        //        return;
        //    var t = sender as Mushroom;
        //    if (t != null)
        //    {
        //        if (t.NextMushroom == null && checkmushroom == t)
        //        {
        //            EndingNow();
        //        }
        //        else
        //        {
        //            if (checkmushroom == t)
        //            {
        //                t.MushroomState = MushroomState.Check;
        //                checkmushroom = t.NextMushroom;
        //            }
        //            else
        //            {
        //                t.MushroomState = MushroomState.Error;
        //                CloseNow();
        //            }
        //        }
        //    }
        //}
        GameState GameState
        {
            get;
            set;
        }
        void Touch_FrameReported(object sender, TouchFrameEventArgs e)
        {
            if (GameState != MushroomPicker.GameState.Ready)
                return;
            var array = e.GetTouchPoints(gamecanves);
            foreach (var item in array)
            {
                switch (item.Action)
                {
                    case TouchAction.Down:
                        var t = CheckMushroom(item.Position);
                        if (t != null)
                        {
                            if (t.NextMushroom == null && checkmushroom == t)
                            {
                                t.MushroomState = MushroomState.Check;
                                EndingNow();
                            }
                            else
                            {
                                if (checkmushroom == t)
                                {
                                    t.MushroomState = MushroomState.Check;
                                    checkmushroom = t.NextMushroom;
                                }
                                else
                                {
                                    //t.MushroomState = MushroomState.Error;
                                    CloseNow();
                                }
                            }
                        }
                        break;
                    case TouchAction.Move:
                        break;
                    case TouchAction.Up:
                        break;
                    default:
                        break;
                }
            }
        }
        public Mushroom CheckMushroom(Point pt)
        {
            foreach (Mushroom item in buffer)
            {
                if (item.Rect.Contains(pt))
                    return item;
            }
            return null;
        }
        void Game_Loaded(object sender, RoutedEventArgs e)
        {
            Loaded -= Game_Loaded;
            foreach (Mushroom item in gamecanves.Children)
            {
                item.SavePos();
                item.AllHided = AllHided;
                item.AllShowed = AllShowed;
                item.AllClosed = AllClosed;
                item.Visibility = System.Windows.Visibility.Collapsed;
            }
            SoundSetting.Current.AddMusicSet(check_Music);
            SoundSetting.Current.AddSoundSet(check_Sound);
            scorePanel.TimeOver = TimeOver;
        }
        private int level;

        public int Level
        {
            get { return level; }
            set
            {
                if (level == value)
                    return;
                level = value;
                textlevel.Text = textlevel1.Text = value.ToString();
                StartGame();
            }
        }

        public void StartGame()
        {
            startroot = null;
            checkmushroom = null;
            buffer.Clear();
            buffer1.Clear();
            foreach (Mushroom t in gamecanves.Children)
            {
                buffer1.Add(t);
                t.Visibility = System.Windows.Visibility.Collapsed;
            }

            //var w = gamecanves.Width / 3;
            //var h = gamecanves.Height / 4;
            for (int i = 0; i < gamecanves.Children.Count; i++)
            {
                Mushroom item = gamecanves.Children[i] as Mushroom;


                item.ReSetPos();
                item.X += Random.Next(-32, 64);
                item.Y += Random.Next(-32, 64);
                item.PrevMushroom = null;
                item.NextMushroom = null;
            }
            var temp = level;
            if (temp >= gamecanves.Children.Count)
            {
                temp = gamecanves.Children.Count;
            }
            Mushroom save = null;
            for (int i = 0; i < temp; i++)
            {
                var mushroom = GetRomeMushroom();
                buffer.Add(mushroom);
                if (save != null)
                {
                    save.NextMushroom = mushroom;
                    mushroom.PrevMushroom = save;
                }
                else
                    startroot = mushroom;
                save = mushroom;
            }
            GameState = MushroomPicker.GameState.Showing;
            startroot.Show();
            checkmushroom = startroot;
        }
        Mushroom startroot;
        Mushroom checkmushroom;
        List<Mushroom> buffer = new List<Mushroom>();
        List<Mushroom> buffer1 = new List<Mushroom>();
        public Mushroom GetRomeMushroom()
        {
            var i = Random.Next() % buffer1.Count;
            var temp = buffer1[i];
            buffer1.RemoveAt(i);
            return temp;
        }
        public void AllHided()
        {
            ShowMessage("Next Level!");
            btn_Go.IsEnabled = true;

            // add  by   DGL
            submitScore.Visibility = Visibility.Visible;
        }
        public void AllShowed()
        {
            GameState = MushroomPicker.GameState.Ready;
            btn_Go.IsEnabled = true;
            scorePanel.StartTime(this.level);

            // add  by   DGL
            this.submitScore.Visibility = Visibility.Visible;

        }
        public void AllClosed()
        {
            ShowMessage("Lose!");
        }
        public void ShowMessage(string message)
        {
            //scorePanel.StopTime();
            if (message != "Lose!")
                Sound.PlayWin();
            this.messageRect.Visibility = System.Windows.Visibility.Visible;
            textmessage.Text = message;
        }

        private void Go_Click(object sender, System.Windows.RoutedEventArgs e)
        {
            Sound.PlayClick();
            if (GameState == MushroomPicker.GameState.Lose)
            {
                //NavigationService.GoBack();
                if (Level > 1)
                {
                    Level -= 1;
                }
                else
                    NavigationService.GoBack();
            }
            else
            {
                Level += 1;


            }
            messageRect.Visibility = System.Windows.Visibility.Collapsed;
            btn_Go.IsEnabled = false;
           
            // add  by   DGL
            submitScore.Visibility = Visibility.Collapsed;

        }
        //结束游戏
        private void EndingNow()
        {
            scorePanel.StopTime();
            GameState = MushroomPicker.GameState.Ending;
            startroot.MushroomState = MushroomState.Hide;
            startValue.Value = scorePanel.ScoreValue;
            endValue.Value = startValue.Value + (level * level * 5);
            Storyboard1.Begin();
        }
        private void CloseNow()
        {
            scorePanel.StopTime();
            GameState = MushroomPicker.GameState.Lose;
            startroot.MushroomState = MushroomState.Error;
        }
        private void TimeOver()
        {
            CloseNow();
        }

        //add by DGL
        private void submitScore_Click(object sender, RoutedEventArgs e)
        {
            if (XLiveGameManager.CurrentSession != null)
            {
                OpenXLive.Features.Leaderboard leaderBoard = new OpenXLive.Features.Leaderboard(XLiveGameManager.CurrentSession, "7304e810-d3a4-43be-92ec-9ba06f4bd0da"); //KeyID' both ends should not have blank space
                leaderBoard.SubmitScoreCompleted += new OpenXLive.Features.AsyncEventHandler(leaderBoard_SubmitScoreCompleted);
                leaderBoard.SubmitScore((int)scorePanel.ScoreValue);
            }

            SubmitAchievement();

            NavigationService.Navigate(new Uri("/MainPage.xaml", UriKind.Relative));
        }

        void leaderBoard_SubmitScoreCompleted(object sender, AsyncEventArgs e)
        {
            if (e.Result.ReturnValue)
            {
                OpenXLive.Features.Leaderboard item = sender as OpenXLive.Features.Leaderboard;
                if (item != null)
                {
                    Dispatcher.BeginInvoke(delegate
                    {
                        MessageBox.Show("Submit score succeed :-)");
                    });
                }
            }
            else
            {
                System.Diagnostics.Debug.WriteLine("Submit score failed :" + e.Result.ErrorMessage);
                Dispatcher.BeginInvoke(delegate
                {
                    MessageBox.Show("Submit failed :-(");
                });
            }
        }

        void SubmitAchievement()
        {
            if (XLiveGameManager.CurrentSession != null)
            {
                if (Level == 7)  // 6 mushroom
                {
                    OpenXLive.Features.Achievement item = new OpenXLive.Features.Achievement(XLiveGameManager.CurrentSession, "545bc777-ad2f-44ff-a59d-1ea2c51cdbc0");
                    item.AwardCompleted += new OpenXLive.Features.AsyncEventHandler(item_AwardCompleted);
                    item.Award();
                }
                else if (Level == 8)
                {
                    OpenXLive.Features.Achievement item = new OpenXLive.Features.Achievement(XLiveGameManager.CurrentSession, "e1dace68-693f-4c38-8187-99fc307cfca3");
                    item.AwardCompleted += new OpenXLive.Features.AsyncEventHandler(item_AwardCompleted);
                    item.Award();
                }
                else if (Level == 9)
                {
                    OpenXLive.Features.Achievement item = new OpenXLive.Features.Achievement(XLiveGameManager.CurrentSession, "8e86fb3a-8888-425e-9153-3f5e0b298e30");
                    item.AwardCompleted += new OpenXLive.Features.AsyncEventHandler(item_AwardCompleted);
                    item.Award();
                }
                else if (Level == 10)
                {
                    OpenXLive.Features.Achievement item = new OpenXLive.Features.Achievement(XLiveGameManager.CurrentSession, "673d6cc3-bcd3-46c5-96ff-4804ceb30668");
                    item.AwardCompleted += new OpenXLive.Features.AsyncEventHandler(item_AwardCompleted);
                    item.Award();
                }
                else if (Level == 11)
                {
                    OpenXLive.Features.Achievement item = new OpenXLive.Features.Achievement(XLiveGameManager.CurrentSession, "e63af4fa-1b1c-44ba-aa85-15cab564526f");
                    item.AwardCompleted += new OpenXLive.Features.AsyncEventHandler(item_AwardCompleted);
                    item.Award();
                }
                else if (Level == 12)
                {
                    OpenXLive.Features.Achievement item = new OpenXLive.Features.Achievement(XLiveGameManager.CurrentSession, "b5f46719-b26c-481c-8d5c-3b1fbeec709e");
                    item.AwardCompleted += new OpenXLive.Features.AsyncEventHandler(item_AwardCompleted);
                    item.Award();
                }
            }
        }

        void item_AwardCompleted(object sender, AsyncEventArgs e)
        {
            if (e.Result.ReturnValue)
            {
                OpenXLive.Features.Achievement item = sender as OpenXLive.Features.Achievement;
                if (item != null)
                {
                    Dispatcher.BeginInvoke(delegate
                    {
                        MessageBox.Show("Submit achievement succeed :-)");
                    });
                }
            }
            else
            {
                System.Diagnostics.Debug.WriteLine("Submit achievement failed :" + e.Result.ErrorMessage);
                Dispatcher.BeginInvoke(delegate
                {
                    MessageBox.Show("Submit achievement failed :-(");
                });
            }

        }
    }
}
